package com.mulesoft.domain.analyzer.structure;

import java.util.LinkedList;
import java.util.List;


public class GraphList {
	protected List<Pair<Character,Integer>> nodes[]; 
	
	@SuppressWarnings("unchecked")
	public GraphList(int size) {
		this.nodes = new List[size];
		for (int i = 0;i < size;i++){
			nodes[i] = new LinkedList<Pair<Character,Integer>>();
		}
	}
	
	public GraphList(String input) {		
		this(getAmountOfNodes(input));
		this.load(input);
	}
	
	public void load(String data) {
		String[] axes = (data.replaceAll(" ", "")).split(",");
		for (String axis : axes) {
			Integer node1 = (int)fromCharToPosition((axis.toCharArray())[0]);
			Pair<Character,Integer> par = new Pair<Character,Integer>(axis.toCharArray()[1],Integer.parseInt(axis.substring(2, 3)));
			this.nodes[node1].add(par);
		}
	}
	
	public void show() {
		for (int i = 0;i < nodes.length;i++){
			System.out.print("[" + fromPositionToChar(i) + "] -> ");
			for (Pair<Character,Integer> destination : nodes[i]) {
				System.out.print(""+ destination.getFirst()+":"+destination.getSecond() + ", ");
			}
			System.out.print("\n");
		}
	}
	
	private static int fromCharToPosition(char aChar) {
		return (aChar - 65);
	}
	
	private static char fromPositionToChar(int pos) {
		return (char) (pos + 65);
	}

	protected static int getAmountOfNodes(String input) {
		String[] axes = (input.replaceAll(" ", "")).split(",");
		int nodePosition = 0;

		for (String axis : axes) {
			if (nodePosition < fromCharToPosition(axis.charAt(0))) {
				nodePosition = fromCharToPosition(axis.charAt(0));
			}

			if (nodePosition < fromCharToPosition(axis.charAt(1))) {
				nodePosition = fromCharToPosition(axis.charAt(1));
			}

		}
		return (nodePosition + 1);
	}
	
	public List<Pair<Character,Integer>> getNeighbors(char city) {
		return this.nodes[fromCharToPosition(city)];
	}

}
